package cn.db.iot.controller;

import cn.db.iot.entity.SysUser;
import cn.db.iot.service.SysUserService;
import cn.db.iot.common.Result;
import cn.db.iot.common.PageResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 用户管理控制器
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private SysUserService sysUserService;

    /**
     * 用户列表查询（分页）
     */
    @GetMapping("/list")
    public Result<PageResult<SysUser>> list(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String keyword) {
        
        Page<SysUser> page = new Page<>(current, size);
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        
        if (keyword != null && !keyword.trim().isEmpty()) {
            queryWrapper.like("name", keyword)
                    .or()
                    .like("real_name", keyword)
                    .or()
                    .like("email", keyword)
                    .or()
                    .like("mobile", keyword);
        }
        
        queryWrapper.eq("del_flag", 0);
        queryWrapper.orderByDesc("create_time");
        
        Page<SysUser> result = sysUserService.page(page, queryWrapper);
        
        PageResult<SysUser> pageResult = new PageResult<>();
        pageResult.setRecords(result.getRecords());
        pageResult.setTotal(result.getTotal());
        pageResult.setCurrent(result.getCurrent());
        pageResult.setSize(result.getSize());
        
        return Result.success(pageResult);
    }

    /**
     * 添加用户
     */
    @PostMapping("/add")
    public Result<String> add(@RequestBody SysUser user) {
        try {
            sysUserService.save(user);
            return Result.success("用户添加成功");
        } catch (Exception e) {
            return Result.error("用户添加失败: " + e.getMessage());
        }
    }

    /**
     * 更新用户
     */
    @PutMapping("/update")
    public Result<String> update(@RequestBody SysUser user) {
        try {
            sysUserService.updateById(user);
            return Result.success("用户更新成功");
        } catch (Exception e) {
            return Result.error("用户更新失败: " + e.getMessage());
        }
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/delete/{id}")
    public Result<String> delete(@PathVariable Long id) {
        try {
            SysUser user = new SysUser();
            user.setId(id);
            user.setDelFlag(-1);
            sysUserService.updateById(user);
            return Result.success("用户删除成功");
        } catch (Exception e) {
            return Result.error("用户删除失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取用户信息
     */
    @GetMapping("/{id}")
    public Result<SysUser> getUserById(@PathVariable Long id) {
        SysUser user = sysUserService.getById(id);
        if (user != null) {
            return Result.success(user);
        }
        return Result.error("用户不存在");
    }

    /**
     * 导出用户数据到Excel
     */
    @GetMapping("/export")
    public void exportExcel(HttpServletResponse response) throws IOException {
        List<SysUser> users = sysUserService.list(new QueryWrapper<SysUser>().eq("del_flag", 0));
        sysUserService.exportToExcel(users, response);
    }
}
